<template>
  <div style="height: 100%;">
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item :label="$t('c.productId')" prop="productId">
        <el-input v-model.number="queryParams.productId" />
      </el-form-item>
      <el-form-item :label="$t('c.productResult')" prop="result">
        <el-select v-model="queryParams.result" clearable>
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('c.timeRange')">
        <el-date-picker v-model="dateRangeAddTime" type="datetimerange" :start-placeholder="$t('c.startTime')"
          :end-placeholder="$t('c.endTime')" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime"
          :shortcuts="dateOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" v-loading="loading" ref="table" border header-cell-class-name="el-table-header-cell"
      highlight-current-row @sort-change="sortChange">
      <el-table-column prop="id" :label="$t('cmmTable.id')" align="center" width="60" />
      <el-table-column :label="$t('cmmTable.productId')" :show-overflow-tooltip="true" align="center">
        <template #default="scope">
          <el-link type="primary" @click="showData(scope.row)">{{ scope.row.productId }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="eid" :label="$t('cmmTable.eid')" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="startTime" :label="$t('cmmTable.startTime')" align="center"
        :show-overflow-tooltip="true" />
      <el-table-column prop="endTime" :label="$t('cmmTable.endTime')" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="costTime" :label="$t('cmmTable.costTime')" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="createTime" :label="$t('cmmTable.createTime')" align="center" />
      <el-table-column prop="checkResult" :label="$t('cmmTable.checkResult')" align="center"
        :show-overflow-tooltip="true" />
      <el-table-column :label="$t('cmmTable.testReport')" align="center">
        <template #default="scope">
          <el-button type="default" :icon="Share" @click="OpenFile(scope.row.id)">Open File</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </div>
  <el-dialog v-model="DataVisible" draggable width="90%" :title="$t('c.paramDetail')" style="height: 600px;">
    <cmm-data v-model:batchCode="batchCode"></cmm-data>
  </el-dialog>
</template>

<script setup name="cmmRecord">
import { listCksCMMDetail,openFile
 } 
from '@/api/business/ckscmmrecord'
import cmmData from '@/views/components/cmmData.vue'
import { ElIcon } from 'element-plus'
import {
Share
} from '@element-plus/icons-vue'
import axios from 'axios'
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const dateRangeAddTime = ref([])

const queryParams = reactive({
  productId:'',
  result: undefined,
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
})
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

function getList(){
  proxy.addDateRange(queryParams, dateRangeAddTime.value, 'AddTime')
  loading.value = true
  listCksCMMDetail(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}
// 状态数据字典
const statusOptions = ref([])
proxy.getDicts('product_result').then((response) => {
  statusOptions.value = response.data
})
// 重置查询操作
function resetQuery(){
  proxy.resetForm("queryRef")
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}
const batchCode = ref('')
const DataVisible = ref(false)
function showData(row) {
  batchCode.value = row.batchCode
  DataVisible.value = true
}

const OpenFile=(id)=>{
  openFile({id:id}).then(res=>{
    try{
    const blob = new Blob([res.data], { type: 'application/pdf' });
    const blobUrl = window.URL.createObjectURL(blob);
    window.open(blobUrl, '_blank');
    setTimeout(() => {
      window.URL.revokeObjectURL(blobUrl);
    }, 30000);
  } catch (error) {
    console.error('打开 PDF 失败:', error);
    let errorMessage = '打开 PDF 失败，请检查路径或联系管理员';
    if (error.response) {
      switch (error.response.status) {
        case 400:
          errorMessage = '路径无效或文件格式错误';
          break;
        case 403:
          errorMessage = '无权限访问该路径';
          break;
        case 404:
          errorMessage = '文件不存在';
          break;
        case 500:
          errorMessage = `服务器错误：${error.response.data}`;
          break;
      }
    }
    alert(errorMessage);
  } finally {
    isLoading.value = false;
  }
  });
   
}

 handleQuery()
</script>